package com.offcn.dao;

import com.offcn.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class BaseDao<T> {
    //声明QueryRunner对象
    private QueryRunner qRunner = new QueryRunner(DruidUtils.getDataSource());

    //封装增删改的方法
    public int dml(String sql, Object... objs) {
        int row = 0;
        try {
            row = qRunner.update(sql, objs);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }
    //封装一个单行多列查询的方法
    public T singleLine(String sql, Class<T> clazz, Object... objs) {
        T t = null;
        try {
            t = qRunner.query(sql, new BeanHandler<T>(clazz), objs);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return t;
    }
    //封装一个多行多列查询的方法
    public List<T> moreLine(String sql, Class<T> clazz, Object... objs) {
        List<T> list = null;
        try {
            list = qRunner.query(sql, new BeanListHandler<T>(clazz), objs);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
    //封装一个单行单列查询的方法
    public Object singleData(String sql, Object... objs) {
        Object object = null;
        try {
            object = qRunner.query(sql, new ScalarHandler(), objs);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return object;
    }
    //封装一个单列多行查询的方法
    public List<Object> singleColumn(String sql, Object... objs) {
        List<Object> objects = null;
        try {
            objects = qRunner.query(sql, new ColumnListHandler(), objs);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return objects;
    }
}
